/**
 * Created by Administrator on 2017/6/29 0029.
 */
"use strict";

angular.module('app.yksensor').controller('YKSensorChartCtrl', function ($scope,sensorHttpS,$http,$cookieStore,$filter) {
    $scope.conf = {};
    $scope.device = {};
    // var originData = [];//原始曲线数据
    // var aimData = [];//目标曲线数据
    var opt=window.location.hash.split('/');
    $scope.null = false;
    //数组中的最大值
    Array.prototype.max = function(){
        return Math.max.apply({},this) 
    }
    //数组中的最小值
    Array.prototype.min = function(){ 
        return Math.min.apply({},this) 
    }
    if(opt[2]){
        // console.log(opt[2]);
        $scope.conf.deviceid = opt[2];
        // $scope.conf.time = "";
        // console.log(GetDateStr(-1)+','+GetDateStr(0));
        $scope.conf.time = GetDateStr(0)+','+GetDateStr(1);
        $("#time_s").val(GetDateStr(0));
        $("#time_e").val(GetDateStr(1));
        if(opt[3]){
            console.log(opt[2]);
            console.log(opt[3]);//设备类型：液位计  流量计 温度计
            getchartdata(opt[3]);

        }
    }
    
    $scope.sends = function(){
        $scope.conf.deviceid = $scope.conf.deviceid == undefined ? "" : $scope.conf.deviceid;
        var timefrom = $('#time_s').val();
        var timeto = $('#time_e').val();
        $scope.conf.time = "";
        if(timefrom == "" && timeto == ""){
            $scope.conf.time = "";
            // console.log(GetDateStr(-1)+','+GetDateStr(0));
            // $scope.conf.time = GetDateStr(-1)+','+GetDateStr(0);
        }else{
            $scope.conf.time = timefrom+","+timeto;
        }
        // console.log($scope.conf.time)
        getchartdata();
    }
    //js获取日期：前天、昨天、今天、明天、后天
    function GetDateStr(AddDayCount) { 
        var dd = new Date(); 
        dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期 
        var y = dd.getFullYear(); 
        var m = dd.getMonth()+1;//获取当前月份的日期 
        var d = dd.getDate(); 
        return y+"-"+m+"-"+d; 
    }
    //获取曲线数据
    function getchartdata(filed){
        var originData = [], TEMP = [], POS = [], FLOW = [];
        var aimData = [];
        var values_arr = [], pos_arr = [], flow_arr = [], temp_arr = [];
        $http.get(baseurls+"/history_data_yk?deviceid=="+$scope.conf.deviceid+"&time="+$scope.conf.time).then(function(res){
            // console.log(res.data)
            if(res.data.ret == 1){
                var len = res.data.info.length;
                for(var i=0; i<len; i++){
                    if(res.data.info[i].sensor_num == 12){//温度数据
                        TEMP.push(res.data.info[i]);
                    }else if(res.data.info[i].sensor_num == 1){//液位数据
                        POS.push(res.data.info[i]);
                    }else if(res.data.info[i].sensor_num == 2){//流量数据
                        FLOW.push(res.data.info[i]);
                    }
                }
            }
            // console.log(TEMP)
            // console.log(POS)
            // console.log(FLOW)

            /** 液位数据处理 **/
            var len2 = POS.length;
            if(len2 != 0){
                var O = {};
                O.label = "液位";
                O.unit = "m3";
                var oData = [];
                for(var j=0; j<len2; j++){ 
                    var pos_time = (new Date(POS[j].time)).getTime();//时间毫秒
                    var o = parseFloat(POS[j].value.replace("[","").replace("]",""))/Math.pow(10,POS[j].point_num);
                    if(o!=0){
                        if(POS[j].dm == 1) o = -o;
                    }
                    oData[j] = [pos_time, o];
                    pos_arr.push(o);//数值比较
                    O.data = oData;//数据
                }
                // console.log(O);
            }
            /** 流量数据处理 **/
            var len4 = FLOW.length;
            if(len4 != 0){
                var F1 = {}, F2 = {};
                F1.label = "瞬时流量", F2.label = "累计流量";
                F1.unit = "m3/s", F2.unit = "m3/s";
                var f1Data = [], f2Data = [];
                for(var j=0; j<len4; j++){ 
                    var flow_time = (new Date(FLOW[j].time)).getTime();//时间毫秒
                    var flows = FLOW[j].value.replace("[","").replace("]","").split(",");
                    flows[0] = parseFloat(flows[0])/Math.pow(10,FLOW[j].point_num);
                    flows[1] = parseFloat(flows[0])/Math.pow(10,FLOW[j].point_num);
                    if(flows[0] != 0){
                        if(FLOW[j].dm == 1) flows[0] = -flows[0];
                    }
                    if(flows[1] != 0){
                        if(FLOW[j].dm == 1) flows[1] = -flows[1];
                    }
                    f1Data[j] = [flow_time, flows[0]];
                    f2Data[j] = [flow_time, flows[1]];
                    flow_arr.push(flows[0]);//数值比较
                    flow_arr.push(flows[1]);//数值比较
                    F1.data = f1Data;//瞬时流量数据
                    F2.data = f2Data;//累计流量数据
                }
                // console.log(F1,F2);
            }
            /** 温度数据处理 **/
            var len3 = TEMP.length;
            if(len3 != 0){
                var t1={}, t2={}, t3={}, t4={},t5={}, t6={},t7={}, t8={}, t9={}, t10={}, t11={}, t12={};
                t1.label = "温度1"; t2.label = "温度2"; t3.label = "温度3"; t4.label = "温度4";
                t5.label = "温度5"; t6.label = "温度6"; t7.label = "温度7"; t8.label = "温度8";
                t9.label = "温度9"; t10.label = "温度10"; t11.label = "温度11"; t12.label = "温度12";
                t1.unit = "°C"; t2.unit = "°C"; t3.unit = "°C"; t4.unit = "°C";
                t5.unit = "°C"; t6.unit = "°C"; t7.unit = "°C"; t8.unit = "°C";
                t9.unit = "°C"; t10.unit = "°C"; t11.unit = "°C"; t12.unit = "°C";
                var t1Data = [], t2Data = [], t3Data = [], t4Data = [],
                    t5Data = [], t6Data = [], t7Data = [], t8Data = [],
                    t9Data = [], t10Data = [], t11Data = [], t12Data = [] ;
                    
                for(var j=0; j<len3; j++){ 
                    var temp_time = (new Date(TEMP[j].time)).getTime();//时间毫秒
                    var arr = TEMP[j].value.replace("[","").replace("]","").split(",");
                    for(var t=0;t<arr.length;t++){
                        var value = parseFloat(arr[t])/Math.pow(10,TEMP[j].point_num);
                        if(value != 0){
                            if(TEMP[j].dm == 1) value = -value;
                        }
                        arr[t] = value;
                    }
                    t1Data[j] = [temp_time, arr[0]]; t2Data[j] = [temp_time, arr[1]]; t3Data[j] = [temp_time, arr[2]];
                    t4Data[j] = [temp_time, arr[3]]; t5Data[j] = [temp_time, arr[4]]; t6Data[j] = [temp_time, arr[5]];
                    t7Data[j] = [temp_time, arr[6]]; t8Data[j] = [temp_time, arr[7]]; t9Data[j] = [temp_time, arr[8]];
                    t10Data[j] = [temp_time, arr[9]]; t11Data[j] = [temp_time, arr[10]]; t12Data[j] = [temp_time, arr[11]];
                    temp_arr = temp_arr.concat(arr);//数值比较
                    t1.data = t1Data; t2.data = t2Data; t3.data = t3Data; t4.data = t4Data;
                    t5.data = t5Data; t6.data = t6Data; t7.data = t7Data; t8.data = t8Data;
                    t9.data = t9Data; t10.data = t10Data; t11.data = t11Data; t12.data = t12Data;
                }
            }
            
            filed = filed == undefined ? "" : filed;
            console.log(filed)
            $scope.null = false;
            if(filed == "pos"){
                if(len2 != 0) aimData = [O];
                values_arr = pos_arr;
            }else if(filed == "flow"){
                if(len4 != 0) aimData = [F1,F2];
                values_arr = flow_arr;
            }else if(filed == "temp"){
                if(len3 != 0) aimData = [t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12];
                values_arr = temp_arr;
            }else{
                if(len2 != 0) aimData.push(O);
                if(len4 != 0) aimData.push(F1,F2);
                if(len3 != 0) aimData.push(t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12);
                values_arr = temp_arr.concat(pos_arr).concat(flow_arr).concat(temp_arr);
            }

            // console.log(values_arr)
            // console.log(values_arr.min(),values_arr.max())
            // console.log(aimData);
            chart_handle(aimData,values_arr.min(),values_arr.max());

        })
    }
    
    function chart_handle(datasets,ymin,ymax){
        var i = 0;
        $.each(datasets, function(key, val) {
            val.color = i;
            ++i;
        });
    
        // insert checkboxes 
        var choiceContainer = $("#choices");
        choiceContainer.html('');//清除选项框的内容
        $.each(datasets, function(key, val) {
            // console.log(key,val)
            choiceContainer.append(
                // "<br/><input type='checkbox' name='" + key +
                // "' checked='checked' id='id" + key + "'></input>" +
                // "<label for='id" + key + "'>"
                // + val.name + "</label>"
                '<div class="col-xs-4 col-md-3 col-lg-2">'+
                    '<div class="well text-center connect">'+
                        '<img src="styles/img/avatars/gril1.png" alt="img" class="margin-bottom-5 margin-top-5">'+
                        // '<div class="margin-bottom-5 margin-top-5" style="border-radius:50% 50% 0; background:#2b92ea; width:50px; height:50px; display:inline-block">'+
                        //     '<strong style="color:#fff; line-height:50px;">'+val.data[val.data.length-1][1].toFixed(1)+'°C</strong>'+
                        // '</div>'+
                        '<br>'+
                        '<span class="font-xs"><b>'+val.label+'</b></span>'+
                        '<br>'+
                        '<span class="onoffswitch">'+
                            '<input type="checkbox" name="'+key+'" checked="checked" class="onoffswitch-checkbox ng-untouched ng-valid ng-dirty ng-valid-parse" id="id'+key+'">'+
                            '<label class="onoffswitch-label" for="id'+key+'">'+
                                '<span class="onoffswitch-inner" data-swchon-text="显示" data-swchoff-text="隐藏"></span>'+
                                '<span class="onoffswitch-switch"></span>'+
                            '</label>'+
                        '</span>'+
                    '</div>'+
                '</div>'
            );
        });
    
        choiceContainer.find("input").click(plotAccordingToChoices);
    
        function plotAccordingToChoices() {
    
            var data = [];
    
            choiceContainer.find("input:checked").each(function () {
                var key = $(this).attr("name");
                if (key && datasets[key]) {
                    data.push(datasets[key]);
                }
            });
    
            if (data.length > 0) {
                $.plot("#tempcharts", data, {
                    series: {
                        lines: {
                            show: true,
                            lineWidth: 2
                        },
                        points:{
                            show: true
                        }
                    },
                    grid: { 
                        hoverable: true, 
                        clickable: true, 
                        tickColor: "#dddddd",
                        borderWidth: 2 
                    },
                    yaxis: {
                        min: ymin,
                        max: ymax,
                        tickDecimals: 2 //y轴小数点位数
                    },
                    xaxis: {
                        mode: "time", //x轴显示时间数据格式
                        tickSize:[1, "day"], //刻度标签会以每1天的间隔显示
                        timeformat: "%Y-%m-%d", //刻度标签要输出的格式
                        // rotateTicks: 45, //jquery.flot.tickrotor 控制x轴过长时的倾斜
                        // labelWidth: 150,
                        // labelHeight: 150,
                        // reserveSpace: true,
                        tickDecimals: 0 //x轴小数点位数
                    },
                    legend: {//???
                        show: false,
                        noColumns: 0,
                            labelFormatter: function (label, series) {
                                return "<font size=\"2\" color=\"white\">" + label + "</font>";
                        },            
                        backgroundColor: "#000",
                        backgroundOpacity: 0.9,
                        labelBoxBorderColor: "#000000",
                        position: "nw"
                    }
                });
    
                function showTooltip(x, y, contents) {
                    $('<div id="tooltip">' + contents + '</div>').css( {
                        position: 'absolute',
                        display: 'none',
                        top: y + 5,
                        left: x + 5,
                        border: '1px solid #fdd',
                        padding: '2px',
                        'background-color': '#dfeffc',
                        opacity: 1,
                        'z-index': 1000
                    }).appendTo("body").fadeIn(200);
                }
    
                var previousPoint = null;
                $("#tempcharts").bind("plothover", function (event, pos, item) {
                    $("#x").text(pos.x);
                    $("#y").text(pos.y.toFixed(2));
    
                    if (item) {
                        if (previousPoint != item.dataIndex) {
                            previousPoint = item.dataIndex;
    
                            $("#tooltip").remove();
                            var x = $filter('date')(item.datapoint[0], 'yyyy-MM-dd HH:mm:ss'),//时间戳毫秒数转换成日期时间
                                y = item.datapoint[1].toFixed(2);
    
                            showTooltip(item.pageX, item.pageY,
                                        item.series.label + " 在 " + x + " 的值是 " + y +" "+item.series.unit);
                        }
                    }
                    else {
                        $("#tooltip").remove();
                            previousPoint = null;
                    }
                }); 
                
            }
        }
        plotAccordingToChoices();
    }

    
});
